import React, { Component } from 'react';
import { Modal, Form, Input, message } from 'antd';
import { changPwd } from './Service';

class ChangePwd extends Component {

  formRef = React.createRef();

  state = { visible: false };
  okHandler = async () => {
    let values = await this.formRef.current.validateFields();
    let res = await changPwd(values);
    if (res.code == 0) {
      message.success('密码修改成功！');
      if (this.props.okHandler) {
        this.props.okHandler();
      }
    } else {
      message.success('旧密码不正确！');
    }
  }

  cancelHandler = () => {
    if (this.props.cancelHandler) {
      this.props.cancelHandler();
    }
  };

  render() {
    const { visible, loading } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };

    return (<Modal title='修改密码' width={620}
                   visible={visible}
                   confirmLoading={loading}
                   destroyOnClose={true}
                   onOk={this.okHandler}
                   onCancel={this.cancelHandler}>
      <Form ref={this.formRef} >
        <Form.Item {...formItemLayout} label="旧密码" name='oldPassword' rules={[{ required: true, message: '请输入旧密码' }]}>
          <Input.Password placeholder="旧密码" visibilityToggle={false} autoComplete='off'/>
        </Form.Item>
        <Form.Item {...formItemLayout} label="新密码" name='newPassword' rules={[{
          required: true, message: '请输入旧密码',
        }, ({ getFieldValue }) => ({
          validator(rule, value) {
            if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,20}$/.test(value)) {
              return Promise.reject('密码必须由8-20位数字和字母组成');
            }
            return Promise.resolve();
          },
        }),
        ]}>
          <Input.Password placeholder="新密码" visibilityToggle={false} autoComplete='off'/>
        </Form.Item>
        <Form.Item {...formItemLayout} label="确认密码" name='rePassword' rules={[{
          required: true, message: '请输入旧密码',
        }, ({ getFieldValue }) => ({
          validator(rule, value) {
            if (getFieldValue('newPassword') === value) {
              return Promise.resolve();
            }
            return Promise.reject('两次输入的密码不一致');
          },
        }),
        ]}>
          <Input.Password placeholder="确认密码" visibilityToggle={false} autoComplete='off'/>
        </Form.Item>
      </Form>
    </Modal>);
  }
}

export default ChangePwd;
